package com.niiwoo.civet.user.service.local;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.user.dao.aggregation.QueryUserBasicInfo;
import com.niiwoo.civet.user.dao.entity.*;
import com.niiwoo.civet.user.dao.mapper.*;
import com.niiwoo.civet.user.dto.request.FeedBackSaveRequestDTO;
import com.niiwoo.civet.user.dto.request.NiiwooScorePageRequestDTO;
import com.niiwoo.civet.user.dto.request.UserBasicInfoRequestDTO;
import com.niiwoo.civet.user.dto.request.customsystem.QueryUserListForSyncRequestDTO;
import com.niiwoo.civet.user.dto.request.customsystem.QueryUserListRequestDTO;
import com.niiwoo.civet.user.dto.response.*;
import com.niiwoo.civet.user.enums.FeedBackSaveEunm;
import com.niiwoo.civet.user.enums.UserBasicEnum;
import com.niiwoo.civet.user.util.HashidsUtil;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.base.helper.StringHelper;
import com.niiwoo.tripod.im.component.IMService;
import com.niiwoo.tripod.im.request.CheckSensitiveImRequest;
import com.niiwoo.tripod.im.request.NiiwooNumberRequest;
import com.niiwoo.tripod.im.response.CheckSensitiveImResponse;
import com.niiwoo.tripod.im.response.NiiwooNumberResponse;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by huangmin on 2017/11/9.
 */
@Service
@Slf4j
public class UserBasicInfoService {

	// 日期格式化
	private FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd");

	@Autowired
	private SnowflakeIdWorker snowflakeIdWorker;
	@Autowired
	private UserBasicInfoMapperExt userBasicInfoMapperExt;
	@Autowired
	private UserNiiwooScoreMapperExt userNiiwooScoreMapperExt;
	@Autowired
	private UserNiiwooScoreRecordMapperExt userNiiwooScoreRecordMapperExt;
	@Autowired
	private UserNickNameLibraryMapperExt userNickNameLibraryMapperExt;
	@Autowired
	private UserFeedBackMapper userFeedBackMapper;
	@Autowired
	private UserInviteCodeMapperExt userInviteCodeMapperExt;
	@Autowired
	private IMService imService;
	@Autowired
	private PrivacyMasks privacyMasks;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	private FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyyMMdd");

	private static final String INVEST_CODE_SEQUENCE_NUMBER_CACHE_KEY = "civet-user:invest-code-sequence-number";

	/**
	 * 展示用户基本信息（用户不存在抛异常）
	 */
	public UserBasicInfoResponseDTO getUserBaseInfo(String userId) {
		UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);
		UserBasicInfoResponseDTO userBasicInfoResponseDTO = new UserBasicInfoResponseDTO();
		if (userBasicInfo != null) {
			userBasicInfoResponseDTO.setUserId(userBasicInfo.getUserId());
			userBasicInfoResponseDTO.setNickName(userBasicInfo.getNickName());
			userBasicInfoResponseDTO.setGender(userBasicInfo.getGender());
			userBasicInfoResponseDTO.setNiiwooCode(userBasicInfo.getNiiwooCode());
			userBasicInfoResponseDTO.setRegisterChannel(userBasicInfo.getRegisterChannel());
			userBasicInfoResponseDTO.setNiiwooScore(userBasicInfo.getNiiwooScore());
			userBasicInfoResponseDTO.setHeadImage(userBasicInfo.getHeadImage());
			userBasicInfoResponseDTO.setMobileNo(privacyMasks.decryptPrivacy(userBasicInfo.getMobileNo()));
			userBasicInfoResponseDTO.setPersonalSign(userBasicInfo.getPersonalSign());
			userBasicInfoResponseDTO.setIdentityTag(userBasicInfo.getIdentityTag());
			userBasicInfoResponseDTO.setWindowFlag(userBasicInfo.getWindowFlag());
			userBasicInfoResponseDTO.setNiiwooFlag(userBasicInfo.getNiiwooFlag());
			userBasicInfoResponseDTO.setCreateTime(userBasicInfo.getCreateTime());
			userBasicInfoResponseDTO.setHeadImage(userBasicInfo.getHeadImage());
			userBasicInfoResponseDTO.setModifyTime(userBasicInfo.getUpdateTime());
			userBasicInfoResponseDTO.setUserSeletctInvestLoanTag(userBasicInfo.getUserSeletctInvestLoanTag());
			if (userBasicInfo.getNiiwooCode() == null || userBasicInfo.getNiiwooCode().equals("")) {
				UserBasicInfo basicInfo = new UserBasicInfo();
				userBasicInfo.setNiiwooCode(getUserNiiwooCode(userId));
				basicInfo.setUserId(userId);
				basicInfo.setNiiwooCode(userBasicInfo.getNiiwooCode());
				userBasicInfoMapperExt.updateByPrimaryKeySelective(basicInfo);
				log.info("通过userId={}###查询你我号niiwooCode={}", userId, userBasicInfo.getNiiwooCode());
			}
		} else {
			log.error("用户不存在###getUserBaseInfo###userId={}", userId);
			throw new BizException("USR10028");
		}
		return userBasicInfoResponseDTO;
	}

	/**
	 * 展示用户基本信息（用户不存返回空）
	 */
	public UserBasicInfoResponseDTO selectUserBaseInfo(String userId) {
		UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);
		if (userBasicInfo == null) {
			log.error("用户不存在###selectUserBaseInfo###userId={}", userId);
			return null;
		}
		UserBasicInfoResponseDTO userBasicInfoResponseDTO = new UserBasicInfoResponseDTO();
		userBasicInfoResponseDTO.setUserId(userBasicInfo.getUserId());
		userBasicInfoResponseDTO.setNickName(userBasicInfo.getNickName());
		userBasicInfoResponseDTO.setGender(userBasicInfo.getGender());
		userBasicInfoResponseDTO.setNiiwooCode(userBasicInfo.getNiiwooCode());
		userBasicInfoResponseDTO.setRegisterChannel(userBasicInfo.getRegisterChannel());
		userBasicInfoResponseDTO.setNiiwooScore(userBasicInfo.getNiiwooScore());
		userBasicInfoResponseDTO.setHeadImage(userBasicInfo.getHeadImage());
		userBasicInfoResponseDTO.setMobileNo(privacyMasks.decryptPrivacy(userBasicInfo.getMobileNo()));
		userBasicInfoResponseDTO.setPersonalSign(userBasicInfo.getPersonalSign());
		userBasicInfoResponseDTO.setIdentityTag(userBasicInfo.getIdentityTag());
		userBasicInfoResponseDTO.setWindowFlag(userBasicInfo.getWindowFlag());
		userBasicInfoResponseDTO.setNiiwooFlag(userBasicInfo.getNiiwooFlag());
		userBasicInfoResponseDTO.setCreateTime(userBasicInfo.getCreateTime());
		userBasicInfoResponseDTO.setHeadImage(userBasicInfo.getHeadImage());
		userBasicInfoResponseDTO.setModifyTime(userBasicInfo.getUpdateTime());

		return userBasicInfoResponseDTO;
	}


	/**
	 * 修改用户昵称
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateUserNickName(UserBasicInfoRequestDTO userBasicInfoRequestDTO, String nickName) {
		UserBasicInfo userBasicInfo = new UserBasicInfo();
		userBasicInfo.setUserId(userBasicInfoRequestDTO.getUserId());
		userBasicInfo.setNickName(userBasicInfoRequestDTO.getNickName());
		if (UserBasicEnum.UserNickNameFlag.INFORMATION_PAGE.getType().equals(userBasicInfoRequestDTO.getUpdateType())) {
			userBasicInfo.setNickNameModifyTime(new Date());
		}
		// 更新用户昵称库
		if (selectUserNickNameLibrary(nickName) > 0) {
			userNickNameLibraryMapperExt.updateByNickName(userBasicInfoRequestDTO.getNickName(), nickName);
		} else {
			UserNickNameLibrary userNickNameLibrary = new UserNickNameLibrary();
			userNickNameLibrary.setUpdateTime(new Date());
			userNickNameLibrary.setNickName(userBasicInfoRequestDTO.getNickName());
			userNickNameLibraryMapperExt.insertSelective(userNickNameLibrary);
		}
		if (userBasicInfoMapperExt.updateByPrimaryKeySelective(userBasicInfo) != 1) {
			throw new BizException("USR10022");
		}
	}

	/**
	 * 修改用户个性签名
	 */

	public void updateUserPersonalSign(UserBasicInfoRequestDTO userBasicInfoRequestDTO) {
		UserBasicInfo userBasicInfo = new UserBasicInfo();
		userBasicInfo.setUserId(userBasicInfoRequestDTO.getUserId());
		userBasicInfo.setPersonalSign(userBasicInfoRequestDTO.getPersonalSign());
		if (userBasicInfoMapperExt.updateByPrimaryKeySelective(userBasicInfo) != 1) {
			throw new BizException("USR10021");
		}
	}


	/**
	 * 查询用户当前你我分
	 */
	public NiiwooScoreResponseDTO selectUserNiiwooScore(String userId) {
		// 查询用户你我分信息
		NiiwooScore niiwooScore = userNiiwooScoreMapperExt.selectNiiwooScoreByUserId(userId);
		if (niiwooScore == null) {
			log.error("你我信用分为空userId={}", userId);
			throw new BizException("USR10016");
		}
		NiiwooScoreResponseDTO niiwooScoreResponseDTO = new NiiwooScoreResponseDTO();
		String niiwooScoreLevel = getNiiwooScoreLevel(niiwooScore.getScore());
		niiwooScoreResponseDTO.setScore(niiwooScore.getScore());
		niiwooScoreResponseDTO.setScoreLevel(niiwooScoreLevel);
		niiwooScoreResponseDTO.setEvaluateTime(niiwooScore.getEvaluateTime());
		niiwooScoreResponseDTO.setScoreDetail(niiwooScore.getScoreDetail());
		// 更新用户基础表中的你我分更新标记
		UserBasicInfo userBasicInfo = new UserBasicInfo();
		userBasicInfo.setUserId(userId);
		userBasicInfo.setNiiwooFlag(UserBasicEnum.UserNiiwooFlag.NOT_UPDATED.getType());
		userBasicInfoMapperExt.updateByPrimaryKeySelective(userBasicInfo);
		return niiwooScoreResponseDTO;
	}

	/**
	 * 查询你我分更新记录
	 */
	public PageResponseDTO selectNiwoScoreRecordListByPage(NiiwooScorePageRequestDTO niiwooScorePageRequestDTO) {
		List<Map<String, Object>> niiwooScorePageList = new ArrayList<>();
		PageResponseDTO pageResponseDTO = new PageResponseDTO();
		int totalCount = userNiiwooScoreRecordMapperExt
				.selectNiiwooScoreRecordCount(niiwooScorePageRequestDTO.getUserId());
		List<NiiwooScoreRecord> niwoScoreRecordList = userNiiwooScoreRecordMapperExt
				.selectNiiwooScoreRecordListByPage(niiwooScorePageRequestDTO);
		for (NiiwooScoreRecord niiwooScoreRecords : niwoScoreRecordList) {
			Map<String, Object> map = new HashMap<>();
			String evaluateTime = dateFormat.format(niiwooScoreRecords.getEvaluateTime());
			String preEvaluateTime = dateFormat.format(niiwooScoreRecords.getPreEvaluateTime());
			String updateRecord = "您现在的你我分为" + niiwooScoreRecords.getScore() + "分，评估时间为" + evaluateTime + "。";
			if (niiwooScoreRecords.getPreScore() != 0) {
				updateRecord = updateRecord + "上次你我分为" + niiwooScoreRecords.getPreScore() + "分，评估时间为" + preEvaluateTime
						+ "。";
			}
			updateRecord = updateRecord + " - 让你的信用更有价值 - ;";
			map.put("updateTime", evaluateTime);
			map.put("updateDesc", updateRecord);
			niiwooScorePageList.add(map);
		}
		pageResponseDTO.setItems(niiwooScorePageList);
		pageResponseDTO.setTotalCount(totalCount);
		return pageResponseDTO;
	}


	/**
	 * 批量存量你我分（天称调用）
	 */
	@Transactional(rollbackFor = Exception.class)
	public int insertBatchNiwoScore(JSONArray scoreArray) {
		List<NiiwooScore> niiwooScoresList = new ArrayList();
		String scoreJsonArray = scoreArray.toJSONString();
		JSONArray jsonArray = JSON.parseArray(scoreJsonArray);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			NiiwooScore niiwooScore = new NiiwooScore();
			niiwooScore.setUserId(jsonObject.getString("userId"));
			niiwooScoresList.add(niiwooScore);
			UserBasicInfo userBasicInfo = new UserBasicInfo();
			userBasicInfo.setUserId(jsonObject.getString("userId"));
			userBasicInfo.setNiiwooScore(jsonObject.getInteger("niwoScore"));
			userBasicInfo.setNiiwooFlag(UserBasicEnum.UserNiiwooFlag.UPDATED.getType());
			// 更新用户信息表中的你我分
			userBasicInfoMapperExt.updateByPrimaryKeySelective(userBasicInfo);
		}
		// 查询用户当前你我分记录
		List<NiiwooScore> getNiiwooScores = userNiiwooScoreMapperExt.selectCurrentNiiwooScore(niiwooScoresList);
		if (getNiiwooScores.size() > 0) {
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				NiiwooScore niiwooScore = getNiiwooScores.get(i);
				NiiwooScoreRecord niiwooScoreRecord = new NiiwooScoreRecord();
				niiwooScoreRecord.setId(snowflakeIdWorker.nextId());
				niiwooScoreRecord.setUserId(jsonObject.getString("userId"));
				niiwooScoreRecord.setScore(jsonObject.getInteger("niwoScore"));
				niiwooScoreRecord.setEvaluateTime(new Date());
				niiwooScoreRecord.setPreScore(niiwooScore.getScore());
				niiwooScoreRecord.setPreEvaluateTime(niiwooScore.getEvaluateTime());
				niiwooScoreRecord.setCreateTime(new Date());
				niiwooScoreRecord.setUpdateTime(new Date());
				// 批量保存你我分更新记录表
				userNiiwooScoreRecordMapperExt.insert(niiwooScoreRecord);
				niiwooScore = new NiiwooScore();
				niiwooScore.setUserId(jsonObject.getString("userId"));
				niiwooScore.setScore(jsonObject.getInteger("niwoScore"));
				niiwooScore.setScoreDetail(jsonObject.getString("radarDetails"));
				niiwooScore.setEvaluateTime(new Date());
				// 更新用户当前你我分表
				userNiiwooScoreMapperExt.updateByUserIdSelective(niiwooScore);
			}
		}
		return getNiiwooScores.size();
	}

	/**
	 * 修改用户头像
	 */
	public void updateHeadImage(UserBasicInfoRequestDTO userBasicInfoDTO) {
		UserBasicInfo userBasicInfo = new UserBasicInfo();
		userBasicInfo.setUserId(userBasicInfoDTO.getUserId());
		userBasicInfo.setHeadImage(userBasicInfoDTO.getHeadImage());
		if (userBasicInfoMapperExt.updateByPrimaryKeySelective(userBasicInfo) != 1) {
			throw new BizException("USR10020");
		}
	}

	/**
	 * 根据ID查询用户
	 */
	public UserBasicInfo selectUserBasicInfo(String userId) {

		return userBasicInfoMapperExt.selectByPrimaryKey(userId);
	}

	/**
	 * 查询用户昵称是否存在
	 */
	public Integer selectUserNickNameLibrary(String nickName) {

		return userNickNameLibraryMapperExt.selectByNickNameCount(nickName);
	}

	/**
	 * 获取用户你我号
	 */
	private String getUserNiiwooCode(String userId) {
		String niiwooCode = "";
		NiiwooNumberResponse response = null;
		NiiwooNumberRequest request = new NiiwooNumberRequest();
		request.setGuid(userId);
		try {
			CompletableFuture<NiiwooNumberResponse> completableFuture = imService.getNiiwooNumber(request);
			response = completableFuture.get(5, TimeUnit.SECONDS);
			log.info("用户获取你我号######返回结果 response={}", JSON.toJSON(response));
			if (response != null && response.getCode() == 0) { // 返回码code: 433失败，0成功
				niiwooCode = response.getImid().toString();
			}
		} catch (Exception e) {
			log.error(String.format("用户获取你我号###异常: userId=%s, response=%s", userId, response), e);
		}
		return niiwooCode;
	}

	/**
	 * 验证昵称敏感词
	 */
	public JSONObject checkSensitiveWords(String word) {
		CheckSensitiveImRequest checkSensitiveImRequest = new CheckSensitiveImRequest();
		JSONObject jsonObject = new JSONObject();
		// 所有类型：0, 提示语:1, 过滤:2
		checkSensitiveImRequest.setSensitiveType(0);
		// 敏感词二级分类 (提示语 欺诈：1)(过滤 色情1, 政治2, 宗教3, 反毒4, 广告5, 其它6, 平台敏感词7)
		checkSensitiveImRequest.setSensitiveSecondaryType(7);
		checkSensitiveImRequest.setSentence(word);
		try {
			CompletableFuture<CheckSensitiveImResponse> completableFuture = imService
					.checkSensitiveWords(checkSensitiveImRequest);
			CheckSensitiveImResponse checkSensitiveImResponse = completableFuture.get();
			// 返回码code: 1失败，0成功
			if (checkSensitiveImResponse.getCode() == 0) {
				jsonObject = checkSensitiveImResponse.getData();
			}
		} catch (Exception e) {
			log.error("IM检测昵称敏感词异常: {}", e.getMessage());
		}
		return jsonObject;
	}

	/**
	 * 根据用户你我分评估等级
	 */
	private String getNiiwooScoreLevel(int socre) {
		if (UserBasicEnum.NiiwooScoreLevel.BAD.getType() > socre) {
			return UserBasicEnum.NiiwooScoreLevel.BAD.getDesc();
		}
		if (UserBasicEnum.NiiwooScoreLevel.COMMONLY.getType() > socre) {
			return UserBasicEnum.NiiwooScoreLevel.COMMONLY.getDesc();
		}
		if (UserBasicEnum.NiiwooScoreLevel.MEDIUM.getType() > socre) {
			return UserBasicEnum.NiiwooScoreLevel.MEDIUM.getDesc();
		}
		if (UserBasicEnum.NiiwooScoreLevel.GOOD.getType() > socre) {
			return UserBasicEnum.NiiwooScoreLevel.GOOD.getDesc();
		}
		return "优秀";
	}

	/**
	 * 获取用户输入数据长度
	 */
	public double getLength(String word) {
		double valueLength = 0;
		String chinese = "[\u4e00-\u9fa5]";
		for (int i = 0; i < word.length(); i++) {
			String temp = word.substring(i, i + 1);
			if (temp.matches(chinese)) {
				valueLength += 1;
			} else {
				valueLength += 0.5;
			}
		}
		return valueLength;
	}


	/**
	 * 获取用户基本信息列表
	 */
	public List<UserBasicInfo> queryListByUserIdSet(Set<String> userIdSet) {
		if (null == userIdSet || userIdSet.isEmpty()) {
			return new ArrayList<>();
		}
		return userBasicInfoMapperExt
				.queryListByUserIdSet(Arrays.asList(userIdSet.toArray(new String[userIdSet.size()])));
	}

	/**
	 * 根据userId查询用户实名信息
	 */
	public QueryBasicInfoResponseDTO selectAuthenticationInfoByUserId(String userId) {
		QueryUserBasicInfo queryUserBasicInfo = userBasicInfoMapperExt.selectAuthenticationInfoByUserId(userId);
		if (queryUserBasicInfo == null) {
			return null;
		}
		QueryBasicInfoResponseDTO responseDTO = new QueryBasicInfoResponseDTO();
		responseDTO.setUserId(queryUserBasicInfo.getUserId());
		responseDTO.setMobileNo(queryUserBasicInfo.getMobileNo());
		responseDTO.setNickName(queryUserBasicInfo.getNickName());
		responseDTO.setHeadImage(queryUserBasicInfo.getHeadImage());
		responseDTO.setRegisterDate(queryUserBasicInfo.getCreateTime());
		responseDTO.setIdcard(queryUserBasicInfo.getIdCard());
		responseDTO.setRealName(queryUserBasicInfo.getRealName());
		return responseDTO;
	}

	/**
	 * 根据userId查询用户职业信息
	 */
	public ImGetUserBasicInfoResponseDTO selectOccupationInfoByUserId(String userId) {

		return userBasicInfoMapperExt.selectOccupationInfoByUserId(userId);
	}

	/**
	 * 更新基础信息
	 * @param basicInfo
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean updateInfo(UserBasicInfo basicInfo) {
		return userBasicInfoMapperExt.updateByPrimaryKeySelective(basicInfo) > 0;
	}


	public String queryUserIdByMobileNo(String mobileNo) {
		return userBasicInfoMapperExt.queryUserIdByMobileNo(mobileNo);
	}

	public String queryUserIdByNickName(String nickName) {
		return userBasicInfoMapperExt.queryUserIdByNickName(nickName);
	}

	public UserBasicInfoResponseDTO queryUserBasicInfoForAsset(String userId) {
		UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByUserIdForAsset(userId);
		UserBasicInfoResponseDTO userBasicInfoResponseDTO = new UserBasicInfoResponseDTO();
		if (Objects.isNull(userBasicInfo)) return userBasicInfoResponseDTO;

		userBasicInfoResponseDTO.setUserId(userBasicInfo.getUserId());
		userBasicInfoResponseDTO.setMobileNo(privacyMasks.decryptPrivacy(userBasicInfo.getMobileNo()));
		userBasicInfoResponseDTO.setRegisterChannel(userBasicInfo.getRegisterChannel());
		return userBasicInfoResponseDTO;
	}

	/**
	 * 意见反馈
	 */
	public boolean feedBackSave(FeedBackSaveRequestDTO requestDTO) {
		UserFeedBack userFeedBack = new UserFeedBack();
		userFeedBack.setId(snowflakeIdWorker.nextId());
		userFeedBack.setUserId(requestDTO.getUserId());
		userFeedBack.setDeviceType(requestDTO.getDeviceType());
		userFeedBack.setType(requestDTO.getType());
		userFeedBack.setContent(requestDTO.getContent());
		userFeedBack.setDeviceSystem(requestDTO.getDeviceSystem());
		userFeedBack.setAppVersion(requestDTO.getAppVersion());
		userFeedBack.setAcceptStatus(FeedBackSaveEunm.UNKNOWN.getValue());
		userFeedBack.setHandleStatus(FeedBackSaveEunm.UNKNOWN.getValue());
		userFeedBack.setCreateTime(new Date());
		userFeedBack.setUpdateTime(new Date());
		return userFeedBackMapper.insertSelective(userFeedBack) > 0;
	}

	/**
	 * 平台信息统计
	 */
	public PlatformStatisticsResponseDTO platformStatisticsInformation() {
		PlatformStatisticsResponseDTO responseDTO = new PlatformStatisticsResponseDTO();
		// 申请借款人数
		long applyLoanUserCount = userBasicInfoMapperExt.selectApplyLoanUserTotal();
		// 注册用户数
		long registerUserCount = userBasicInfoMapperExt.selectRegisteredUsersCount();
		// 今日注册用户数
		long todayRegisterUserCount = userBasicInfoMapperExt.selectRegisteredUsersCountToday();
		responseDTO.setApplyLoanUserCount(applyLoanUserCount);
		responseDTO.setRegisterUserCount(registerUserCount);
		responseDTO.setTodayRegisterUserCount(todayRegisterUserCount);
		return responseDTO;
	}

	/**
	 * 客服系统查询用户信息
	 * @param queryUserListRequestDTO
	 * @return
	 */
	public List<UserBasicInfo> queryCustomSystemUserList(QueryUserListRequestDTO queryUserListRequestDTO) {
		return userBasicInfoMapperExt.queryCustomSystemUserList(queryUserListRequestDTO);
	}

	/**
	 * 客服系统同步用户信息
	 * @param queryUserListForSyncRequestDTO
	 * @return
	 */
	public List<UserBasicInfo> queryCustomSystemUserListForSync(
			QueryUserListForSyncRequestDTO queryUserListForSyncRequestDTO) {
		return userBasicInfoMapperExt.queryCustomSystemUserListForSync(queryUserListForSyncRequestDTO);
	}

	/**
	 * 获取邀请码
	 * 
	 * @param userId
	 * @return
	 */
	@Transactional
	public String getInviteCode(String userId) {
		// 查询用户邀请码信息
		UserInviteCode userInviteCode = userInviteCodeMapperExt.selectByPrimaryKey(userId);
		if (userInviteCode != null) {
			return userInviteCode.getCode();
		}

		// 生成邀请码
		Long sequenceNumber = getInviteCodeSequenceNumber();
		String salt = StringHelper.genRandomStr(6);
		String code = HashidsUtil.getHashidsString(sequenceNumber, salt, 6);

		// 生成邀请记录
		userInviteCode = new UserInviteCode();
		userInviteCode.setUserId(userId);
		userInviteCode.setCode(code);
		userInviteCode.setSequenceNumber(sequenceNumber);
		userInviteCode.setCreateTime(new Date());
		userInviteCodeMapperExt.insertSelective(userInviteCode);

		return code;
	}

	private Long getInviteCodeSequenceNumber() {
		// 存在
		if (redisTemplate.hasKey(INVEST_CODE_SEQUENCE_NUMBER_CACHE_KEY)) {
			return redisTemplate.opsForValue().increment(INVEST_CODE_SEQUENCE_NUMBER_CACHE_KEY, 1);	
		}

		// 不存在查询当前最大序号，并添加到缓存中
		Long sequenceNumber = userInviteCodeMapperExt.selectMaxSequenceNumber();
		if (null != sequenceNumber) {
			redisTemplate.opsForValue().set(INVEST_CODE_SEQUENCE_NUMBER_CACHE_KEY, String.valueOf(sequenceNumber));
		} else {
			redisTemplate.opsForValue().set(INVEST_CODE_SEQUENCE_NUMBER_CACHE_KEY, "1");
		}
		return redisTemplate.opsForValue().increment(INVEST_CODE_SEQUENCE_NUMBER_CACHE_KEY, 1);
	}
}

